Marie-Hélène Burle
January 27, 2022
Many drawings in this webinar come from the book:
The section on storage is also highly inspired by it
You need to have Python & PyTorch installed
Additionally, you might want to use an IDE such as elpy if you are an Emacs user, JupyterLab, etc.
Note that PyTorch does not yet support Python 3.10 except in some Linux distributions or on systems where a wheel has been built For the time being, you might have to use it with Python 3.9
In the cluster terminal:
avail_wheels "torch*" # List available wheels & compatible Python versions
module avail python # List available Python versions
module load python/3.9.6 # Load a sensible Python version
virtualenv --no-download env # Create a virtual env
source env/bin/activate # Activate the virtual env
pip install --no-index --upgrade pip # Update pip
pip install --no-index torch # Install PyTorchYou can then launch jobs with sbatch or salloc
Leave the virtual env with the command: deactivate
Modified from Stevens, E., Antiga, L., & Viehmann, T. (2020). Deep learning with PyTorch. Manning Publications
Modified from Stevens, E., Antiga, L., & Viehmann, T. (2020). Deep learning with PyTorch. Manning Publications
PyTorch tensors are Python objects holding multidimensional arrays
Stevens, E., Antiga, L., & Viehmann, T. (2020). Deep learning with PyTorch. Manning Publications
Can run on accelerators (GPUs, TPUs…)
Keep track of computation graphs, allowing automatic differentiation
Future plan for sharded tensors to run distributed computations
PyTorch is foremost a deep learning library
In deep learning, the information contained in objects of interest (e.g. images, texts, sounds) is converted to floating-point numbers (e.g. pixel values, token values, frequencies)
As this information is complex, multiple dimensions are required (e.g. two dimensions for the width & height of an image, plus one dimension for the RGB colour channels)
Additionally, items are grouped into batches to be processed together, adding yet another dimension
Multidimensional arrays are thus particularly well suited for deep learning
Artificial neurons perform basic computations on these tensors
Their number however is huge & computing efficiency is paramount
GPUs/TPUs are particularly well suited to perform many simple operations in parallel
The very popular NumPy library has, at its core, a mature multidimensional array object well integrated into the scientific Python ecosystem
But the PyTorch tensor has additional efficiency characteristics ideal for machine learning & it can be converted to/from NumPy’s ndarray if needed
In Python, collections (lists, tuples) are groupings of boxed Python objects
PyTorch tensors & NumPy ndarrays are made of unboxed C numeric types
Stevens, E., Antiga, L., & Viehmann, T. (2020). Deep learning with PyTorch. Manning Publications
They are usually contiguous memory blocks, but the main difference is that they are unboxed: floats will thus take 4 (32-bit) or 8 (64-bit) bytes each
Boxed values take up more memory (memory for the pointer + memory for the primitive)
Stevens, E., Antiga, L., & Viehmann, T. (2020). Deep learning with PyTorch. Manning Publications
Under the hood, the values of a PyTorch tensor are stored as a torch.Storage instance which is a one-dimensional array
The storage can be indexed
To view a multidimensional array from storage, we need metadata:
the size (shape in NumPy) sets the number of elements in each dimension
the offset indicates where the first element of the tensor is in the storage
the stride establishes the increment between each element
Stevens, E., Antiga, L., & Viehmann, T. (2020). Deep learning with PyTorch. Manning Publications
Multiple tensors can use the same storage, saving a lot of memory since the metadata is a lot lighter than a whole new array
Stevens, E., Antiga, L., & Viehmann, T. (2020). Deep learning with PyTorch. Manning Publications
= flipping the stride elements around
Stevens, E., Antiga, L., & Viehmann, T. (2020). Deep learning with PyTorch. Manning Publications
torch.t() is a shorthand for torch.transpose(0, 1):
While torch.t() only works for 2D tensors, torch.transpose() can be used to transpose 2 dimensions in tensors of any number of dimensions
Since PyTorch tensors were built with utmost efficiency in mind for neural networks, the default data type is 32-bit floating points
This is sufficient for accuracy & much faster than 64-bit floating points
Note that, by contrast, NumPy ndarrays use 64-bit as their default
| torch.float16 / torch.half | 16-bit / half-precision floating-point | |
| torch.float32 / torch.float | 32-bit / single-precision floating-point | |
| torch.float64 / torch.double | 64-bit / double-precision floating-point | |
| torch.uint8 | unsigned 8-bit integers | |
| torch.int8 | signed 8-bit integers | |
| torch.int16 / torch.short | signed 16-bit integers | |
| torch.int32 / torch.int | signed 32-bit integers | |
| torch.int64 / torch.long | signed 64-bit integers | |
| torch.bool | boolean |
t = torch.rand(2, 3); print(t)
t.dtype # Remember that the default dtype for PyTorch tensors is float32
t2 = t.type(torch.float64); print(t2) # If dtype ≠ default, it is printed
t2.dtypetorch.tensor: Input individual valuestorch.arange: Similar to range but creates a 1D tensortorch.linspace: 1D linear scale tensortorch.logspace: 1D log scale tensortorch.rand: Random numbers from a uniform distribution on [0, 1)torch.randn: Numbers from the standard normal distributiontorch.randperm: Random permutation of integerstorch.empty: Uninitialized tensortorch.zeros: Tensor filled with 0torch.ones: Tensor filled with 1torch.eye: Identity matrixtorch.manual_seed(0) # If you want to reproduce the result
torch.rand(1)
torch.manual_seed(0) # Run before each operation to get the same result
torch.rand(1).item() # Extract the value from a tensort = torch.rand(2, 3); print(t)
torch.zeros_like(t) # Matches the size of t
torch.ones_like(t)
torch.randn_like(t)torch.arange(2, 10, 4) # From 2 to 10 in increments of 4
torch.linspace(2, 10, 4) # 4 elements from 2 to 10 on the linear scale
torch.logspace(2, 10, 4) # Same on the log scale
torch.randperm(4)
torch.eye(3)x = torch.rand(3, 4)
x[:] # With a range, the comma is implicit: same as x[:, ]
x[:, 2]
x[1, :]
x[2, 3]x[-1:] # Last element (implicit comma, so all columns)
x[-1] # No range, no implicit comma: we are indexing
# from a list of tensors, so the result is a one dimensional tensor
# (Each dimension is a list of tensors of the previous dimension)
x[-1].size() # Same number of dimensions than x (2 dimensions)
x[-1:].size() # We dropped one dimensionx[0:1] # Python ranges are inclusive to the left, not the right
x[:-1] # From start to one before last (& implicit comma)
x[0:3:2] # From 0th (included) to 3rd (excluded) in increment of 2While indexing elements of a tensor to extract some of the data as a final step of some computation is fine, you should not use indexing to run operations on tensor elements in a loop as this would be extremely inefficient
Instead, you want to use vectorized operations
Since PyTorch tensors are homogeneous (i.e. made of a single data type), as with NumPy’s ndarrays, operations are vectorized & thus staggeringly fast
NumPy is mostly written in C & PyTorch in C++. With either library, when you run vectorized operations on arrays/tensors, you don’t use raw Python (slow) but compiled C/C++ code (much faster)
Here is an excellent post explaining Python vectorization & why it makes such a big difference
Raw Python method
# Create tensor. We use float64 here to avoid truncation errors
t = torch.rand(10**6, dtype=torch.float64)
# Initialize the sum
sum = 0
# Run loop
for i in range(len(t)): sum += t[i]
# Print result
print(sum)Vectorized function
Both methods give the same result
This is why we used float64:
While the accuracy remains excellent with float32 if we use the PyTorch function torch.sum(), the raw Python loop gives a fairly inaccurate result
Let’s compare the timing with PyTorch built-in benchmark utility
Now we can create the timers
Let’s time 100 runs to have a reliable benchmark
I ran the code on my laptop with a dedicated GPU & 32GB RAM
Timing of raw Python loop
Timing of vectorized function
Speedup:
The vectorized function runs more than 7,000 times faster!!!
We will talk about GPUs in detail later
Timing of raw Python loop on GPU (actually slower on GPU!)
Timing of vectorized function on GPU (here we do get a speedup)
Speedup:
On GPUs, it is even more important not to index repeatedly from a tensor
On GPUs, the vectorized function runs almost 90,000 times faster!!!
t1 = torch.arange(1, 5).view(2, 2); print(t1)
t2 = torch.tensor([[1, 1], [0, 0]]); print(t2)
t1 + t2 # Operation performed between elements at corresponding locations
t1 + 1 # Operation applied to each element of the tensortensor([[[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]],
[[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]]])
tensor(24.)Other reduction functions (e.g. mean) behave the same way
With operators post-fixed with _:
t1 = torch.tensor([1, 2]); print(t1)
t2 = torch.tensor([1, 1]); print(t2)
t1.add_(t2); print(t1)
t1.zero_(); print(t1)t1 = torch.ones(1); t1, hex(id(t1))
t1.add_(1); t1, hex(id(t1)) # In-place operation: same address
t1 = t1.add(1); t1, hex(id(t1)) # Reassignment: new address in memory
t1 = t1 + 1; t1, hex(id(t1)) # Reassignment: new address in memoryt = torch.tensor([[1, 2, 3], [4, 5, 6]]); print(t)
t.size()
t.view(6)
t.view(3, 2)
t.view(3, -1) # Same: with -1, the size is inferred from other dimensionst1 = torch.tensor([[1, 2, 3], [4, 5, 6]]); print(t1)
t2 = t1.t(); print(t2)
t3 = t1.view(3, 2); print(t3)t1 = torch.randperm(5); print(t1)
t2 = torch.randperm(5); print(t2)
t1 > 3 # Test each element
t1 < t2 # Test corresponding pairs of elementsPyTorch tensors can be converted to NumPy ndarrays & vice-versa in a very efficient manner as both objects share the same memory
Remember that PyTorch tensors use 32-bit floating points by default
(because this is what you want in neural networks)
But NumPy defaults to 64-bit
Depending on your workflow, you might have to change dtype
import numpy as np
a = np.random.rand(2, 3); print(a)
a_pt = torch.from_numpy(a); print(a_pt) # From ndarray to tensor[[0.55892276 0.06026952 0.72496545]
[0.65659463 0.27697739 0.29141587]]
tensor([[0.5589, 0.0603, 0.7250],
[0.6566, 0.2770, 0.2914]], dtype=torch.float64)Here again, you might have to change dtype
t & t_np are objects of different Python types, so, as far as Python is concerned, they have different addresses
However—that’s quite confusing—they share an underlying C array in memory & modifying one in-place also modifies the other
Lastly, as NumPy only works on CPU, to convert a PyTorch tensor allocated to the GPU, the content will have to be copied to the CPU first
All functions from numpy.linalg implemented (with accelerator & automatic differentiation support)
Some additional functions
Requires torch >= 1.9
Linear algebra support was less developed before the introduction of this module
Let’s have a look at an extremely basic example:
2x + 3y - z = 5
x - 2y + 8z = 21
6x + y - 3z = -1
We are looking for the values of x, y, & z that would satisfy this system
We create a 2D tensor A of size (3, 3) with the coefficients of the equations
& a 1D tensor b of size 3 with the right hand sides values of the equations
A = torch.tensor([[2., 3., -1.], [1., -2., 8.], [6., 1., -3.]]); print(A)
b = torch.tensor([5., 21., -1.]); print(b)Solving this system is as simple as running the torch.linalg.solve function:
Our solution is:
x = 1
y = 2
z = 3
Here is another simple example:
tensor([[ 1.5091, 2.0820, 1.7067, 2.3804], # A (coefficients)
[-1.1256, -0.3170, -1.0925, -0.0852],
[ 0.3276, -0.7607, -1.5991, 0.0185],
[-0.7504, 0.1854, 0.6211, 0.6382]])
tensor([-1.0886, -0.2666, 0.1894, -0.2190]) # b (right hand side values)
tensor([ 0.1992, -0.7011, 0.2541, -0.1526]) # x (our solution)
True # VerificationA = torch.randn(2, 3, 3) # Must be batches of square matrices
B = torch.randn(2, 3, 5) # Dimensions must be compatible
X = torch.linalg.solve(A, B); print(X)
torch.allclose(A @ X, B)It is faster & more numerically stable to solve a system of linear equations directly than to compute the inverse matrix first
Limit matrix inversions to situations where it is truly necessary
A = torch.rand(2, 3, 3) # Batch of square matrices
A_inv = torch.linalg.inv(A) # Batch of inverse matrices
A @ A_inv # Batch of identity matricestorch.linalg contains many more functions:
torch.tensordot which generalizes matrix products
torch.linalg.tensorsolve which computes the solution X to the system torch.tensordot(A, X) = B
torch.linalg.eigvals which computes the eigenvalues of a square matrix
and more
Tensor data can be placed in the memory of various processor types:
the RAM of CPU
the RAM of a GPU with CUDA support
the RAM of a GPU with AMD’s ROCm support
the RAM of an XLA device (e.g. Cloud TPU) with the torch_xla package
The values for the device attributes are:
CPU: 'cpu'
GPU (CUDA & AMD’s ROCm): 'cuda'
XLA: xm.xla_device()
This last option requires to load the torch_xla package first:
By default, tensors are created on the CPU
Printed tensors only display attributes with values ≠ default values
You can create a tensor on an accelerator by specifying the device attribute
You can also make copies of a tensor on other devices
# Make a copy of t1 on the GPU
t1_gpu = t1.to(device='cuda'); print(t1_gpu)
t1_gpu = t1.cuda() # Same as above written differently
# Make a copy of t2_gpu on the CPU
t2 = t2_gpu.to(device='cpu'); print(t2)
t2 = t2_gpu.cpu() # For the altenative formIf you have multiple GPUs, you can optionally specify which one a tensor should be created on or copied to
Let’s compare the timing of some matrix multiplications on CPU & GPU with PyTorch built-in benchmark utility
# Load utility
import torch.utils.benchmark as benchmark
# Define tensors on the CPU
A = torch.randn(500, 500)
B = torch.randn(500, 500)
# Define tensors on the GPU
A_gpu = torch.randn(500, 500, device='cuda')
B_gpu = torch.randn(500, 500, device='cuda')I ran the code on my laptop with a dedicated GPU & 32GB RAM
Let’s time 100 runs to have a reliable benchmark
A @ B
2.29 ms
1 measurement, 100 runs , 1 thread
A_gpu @ B_gpu
108.02 us
1 measurement, 100 runs , 1 threadSpeedup:
This computation was 21 times faster on my GPU than on CPU
By replacing 500 with 5000, we get:
A @ B
2.21 s
1 measurement, 100 runs , 1 thread
A_gpu @ B_gpu
57.88 ms
1 measurement, 100 runs , 1 threadSpeedup:
The larger the computation, the greater the benefit: now 38 times faster
PyTorch already allows for distributed training of ML models
The implementation of distributed tensor operations—for instance for linear algebra—is in the work through the use of a ShardedTensor primitive that can be sharded across nodes
See also this issue for more comments about upcoming developments on (among other things) tensor sharding